<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="学生账号" prop="userName">
              <el-input v-model="queryParams.userName" placeholder="请输入学生账号" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="学生昵称" prop="nickName">
              <el-input v-model="queryParams.nickName" placeholder="请输入学生昵称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="学生邮箱" prop="email">
              <el-input v-model="queryParams.email" placeholder="请输入学生邮箱" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="手机号码" prop="phonenumber">
              <el-input v-model="queryParams.phonenumber" placeholder="请输入手机号码" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="注册时间" prop="createTime">
              <el-date-picker
                v-model="dateRange"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="YYYY-MM-DD"
                @change="handleDateRangeChange"
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['bykt:user:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['bykt:user:edit']">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['bykt:user:remove']">删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain :disabled="single" @click="enableDisable(0)" v-hasPermi="['bykt:user:remove']">启用</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain :disabled="single" @click="enableDisable(1)" v-hasPermi="['bykt:user:remove']">禁用</el-button>
          </el-col>

          <el-col :span="1.5">
            <el-button type="primary" plain icon="Download" @click="visible = true">导入文件</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Upload" @click="handleExport" v-hasPermi="['bykt:user:export']">导出模版</el-button>
          </el-col>
    <import-export
      v-model="showImportExport"
      title="课程导入导出"
      :import-types="importTypes"
      :export-types="exportTypes"
      @success="handleImportSuccess"
    />
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

      </template>

      <el-table v-loading="loading" :data="userList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="学生账号" align="center" prop="userName" />
        <el-table-column label="学生昵称" align="center" prop="nickName" />
        <el-table-column label="学生邮箱" align="center" prop="email" />
        <el-table-column label="手机号码" align="center" prop="phonenumber" />
        <el-table-column label="注册时间" align="center" prop="createTime" />
        <el-table-column label="学生性别" align="center" prop="sex" >
          <template #default="scope">
              <span>{{ scope.row.sex == 0 ? '男':"女"}}</span>
            </template>
          </el-table-column>

        <el-table-column label="帐号状态" align="center" prop="status" >
          <template #default="scope">
              <span>{{ scope.row.status == 0 ? '正常' : "停用"}}</span>
            </template>
          </el-table-column>

        <el-table-column label="备注" align="center" prop="remark" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['bykt:user:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['bykt:user:remove']"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 添加或修改学生信息对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="500px" append-to-body>
      <el-form ref="userFormRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="学生账号" prop="userName">
          <el-input v-model="form.userName" placeholder="请输入学生账号" />
        </el-form-item>
        <el-form-item label="学生昵称" prop="nickName">
          <el-input v-model="form.nickName" placeholder="请输入学生昵称" />
        </el-form-item>
        <el-form-item label="学生邮箱" prop="email">
          <el-input v-model="form.email" placeholder="请输入学生邮箱" />
        </el-form-item>
        <el-form-item label="手机号码" prop="phonenumber">
          <el-input v-model="form.phonenumber" placeholder="请输入手机号码" />
        </el-form-item>
        <!-- <el-form-item label="头像地址" prop="avatar">
          <el-input v-model="form.avatar" placeholder="请输入头像地址" />
        </el-form-item> -->
        <el-form-item label="头像地址" prop="avatar">
              <el-upload
                :headers="uploadHeaders"
                drag
                action="/dev-api/ossUpload/uploadImage"
                :on-progress="handleImageProgress"
                :on-success="handleImageSuccess"
                :before-upload="beforeImageUpload"
                :on-remove="handleImageRemove"
                :file-list="imageFileList"
                accept=".jpg,.png"
                list-type="picture-card"
              >
                <el-icon class="avatar-uploader-icon"><Plus /></el-icon>

                <template #file="{ file }">
                  <div>
                    <img class="el-upload-list__item-thumbnail" :src="file.url" alt="" />
                    <span class="el-upload-list__item-actions">
                      <span
                        class="el-upload-list__item-delete"
                        @click="handleImageRemove(file)"
                      >
                        <el-icon><Delete /></el-icon>
                      </span>
                    </span>
                  </div>
                </template>
              </el-upload>
            </el-form-item>
        <el-form-item v-if="dialog.title != '修改学生信息'" label="密码" prop="password">
          <el-input v-model="form.password" placeholder="请输入密码" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
            <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <ImportXlsxs :visible="visible" :url="url" @parentFunction="parentFunction"></ImportXlsxs>
  </div>
</template>

<script setup name="User">
import { listUser, getUser, delUser, addUser, updateUser } from '@/api/bykt/student';
import { getCurrentInstance, ref, reactive, toRefs, onMounted } from 'vue';
import { getToken } from '@/utils/auth';
import ImportXlsxs from '@/components/importXlsxs/index.vue'
const { proxy } = getCurrentInstance();

const visible = ref(false);
const showImportExport = ref(false)
const userList = ref([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const dateRange = ref([]);
const queryFormRef = ref(null);
const userFormRef = ref(null);
const imageFileList = ref([]);
const dialog = reactive({
  visible: false,
  title: ''
});
const imageProgress = ref(0);
const uploadHeaders = ref({
  'Authorization': `Bearer ` + getToken(), // JWT 示例
});
const initFormData = {
  userId: undefined,
  deptId: undefined,
  userName: undefined,
  nickName: undefined,
  userType: undefined,
  email: undefined,
  phonenumber: undefined,
  sex: undefined,
  avatar: undefined,
  password: undefined,
  status: undefined,
  loginIp: undefined,
  loginDate: undefined,
  remark: undefined
};

const data = reactive({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    deptId: undefined,
    userName: undefined,
    nickName: undefined,
    userType: undefined,
    email: undefined,
    phonenumber: undefined,
    sex: undefined,
    avatar: undefined,
    password: undefined,
    status: undefined,
    loginIp: undefined,
    loginDate: undefined,
    beginCreateTime: undefined,  // 添加开始时间
    endCreateTime: undefined,    // 添加结束时间
    params: {}
  },
  rules: {
    userId: [
      { required: true, message: "学生ID不能为空", trigger: "blur" }
    ],
    userName: [
      { required: true, message: "学生账号不能为空", trigger: "blur" }
    ],
    nickName: [
      { required: true, message: "学生昵称不能为空", trigger: "blur" }
    ],
  }
});

const enableDisable = (row) => {
  const selectedUser = userList.value.find(user => user.userId === ids.value[0]);
  updateUser({
    userId: ids.value[0],
    status: row,
    userName: selectedUser.userName,
    nickName: selectedUser.nickName
  }).then(res => {
    proxy.$modal.msgSuccess("操作成功");
    getList();
  })
}

const { queryParams, form, rules } = toRefs(data);
// http://localhost/dev-api/ossUpload/uploadImage

const url = ref('http://localhost/dev-api/bykt/user/importData');
// 配置导入类型
const importTypes = [
  { type: 'course', label: '课程', importUrl: '/bykt/course/import' },
  { type: 'chapter', label: '章节', importUrl: '/bykt/chapter/import' },
  { type: 'video', label: '视频', importUrl: '/bykt/video/import' }
]

// 配置导出类型
const exportTypes = [
  { type: 'course', label: '课程', exportUrl: '/bykt/course/export' },
  { type: 'chapter', label: '章节', exportUrl: '/bykt/chapter/export' },
  { type: 'video', label: '视频', exportUrl: '/bykt/video/export' }
]

const parentFunction = (data) => {
  visible.value = false
}
// 导入成功回调
const handleImportSuccess = (response) => {
  console.log('导入成功', response)
  // 可以在这里刷新列表等操作
}
const handleDateRangeChange = (val) => {
  if (val) {
    queryParams.value.beginCreateTime = val[0];
    queryParams.value.endCreateTime = val[1];
  } else {
    queryParams.value.beginCreateTime = undefined;
    queryParams.value.endCreateTime = undefined;
  }
};
/** 查询学生信息列表 */
const getList = async () => {
  loading.value = true;
  // if(queryParams.value.createTime[0]) {
  //   delete queryParams.value.createTime[0];
  // }
  // if(queryParams.value.createTime[1]) {
  //   delete queryParams.value.createTime[1];
  // }
  const res = await listUser(queryParams.value);
  userList.value = res.rows;
  total.value = res.total;
  loading.value = false;
}

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
}

/** 表单重置 */
const reset = () => {
  data.form = { ...initFormData };
  if (userFormRef.value) {
    userFormRef.value.resetFields();
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
const resetQuery = () => {
  if (queryFormRef.value) {
    queryFormRef.value.resetFields();
  }
  dateRange.value = []; // 重置日期范围
  queryParams.value.beginCreateTime = undefined;
  queryParams.value.endCreateTime = undefined;
  handleQuery();
}

/** 多选框选中数据 */
const handleSelectionChange = (selection) => {
  ids.value = selection.map(item => item.userId);
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  imageFileList.value = []
  dialog.visible = true;
  dialog.title = "添加学生信息";

}

/** 修改按钮操作 */
const handleUpdate = async (row) => {
  reset();
  const _userId = row?.userId || ids.value[0];
  const res = await getUser(_userId);
  Object.assign(data.form, res.data);
  if (form.value.avatar) { // 修改这里，使用 avatar 而不是 image
      imageFileList.value = [{
        name: '已上传图片',
        url: form.value.avatar // 修改这里，使用 avatar 而不是 image
      }];
    } else {
      imageFileList.value = [];
    }
  dialog.visible = true;
  dialog.title = "修改学生信息";
}

/** 提交按钮 */
const submitForm = () => {
  console.log(data.form)
  userFormRef.value.validate(async (valid) => {
    if (valid) {
      buttonLoading.value = true;
      try {
        if (data.form.userId) {
          await updateUser(data.form);
        } else {
          await addUser(data.form);
        }
        proxy.$modal.msgSuccess("操作成功");
        dialog.visible = false;
        await getList();
      } finally {
        buttonLoading.value = false;
      }
    }
  });
}
const handleImageSuccess = (response, file) => {
  imageProgress.value = 0;
  // 清空现有文件列表，然后添加新上传的文件
  imageFileList.value = [];
  // 添加延迟，确保DOM更新
  setTimeout(() => {
    imageFileList.value = [{
      name: file.name,
      url: response.data
    }];
    data.form.avatar = response.data;
  }, 10);
}

const handleImageRemove = () => {
  // 清空图片字段
  form.value.avatar = "";
  imageFileList.value = [];
}

const beforeImageUpload = (file) => {
  const isImage = file.type === 'image/jpeg' || file.type === 'image/png';
  if (!isImage) {
    ElMessage.error('只能上传JPG/PNG格式的图片!');
    return false;
  }

  return true;
}

const handleImageProgress = (event) => {
  imageProgress.value = event.percent;
}
/** 删除按钮操作 */
const handleDelete = async (row) => {
  const _userIds = row?.userId || ids.value;
  await proxy.$modal.confirm('是否确认删除学生信息编号为"' + _userIds + '"的数据项？');
  await delUser(_userIds);
  proxy.$modal.msgSuccess("删除成功");
  await getList();
}

/** 导出按钮操作 */
const handleExport = () => {
  proxy.download('bykt/user/export', {
    ...queryParams.value
  }, `学员模版_${new Date().getTime()}.xlsx`);
}

onMounted(() => {
  getList();
});
</script>
<style scoped>
.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100%;
  height: 64px;
  text-align: center;
}
</style>
